import sh from 'shelljs';
import chalk from 'chalk';
import commander from 'commander';
import { paramCase, pascalCase } from 'change-case';
import path from 'path';
import fs from 'fs';

commander
    .requiredOption('-n, --name <NewComponentName>', 'new component name')
    .requiredOption('-p, --path <NewComponentPath>', 'new component path')
    .parse(process.argv);

const options = commander.opts();

async function main() {
    if (typeof options.name !== 'string' || !options.path) {
        console.log(commander.help());
        process.exit();
    }

    console.log(
        chalk.blue(
            `### INFO: Creating component ${pascalCase(options.name)} at ${
                options.path
            }`,
        ),
    );

    const newComponentFolderPath = path.join(
        options.path,
        paramCase(options.name),
    );
    const newComponentFilePath = path.join(
        newComponentFolderPath,
        `${paramCase(options.name)}.vue`,
    );
    const templateComponentFilePath = path.join(
        newComponentFolderPath,
        '_template.vue',
    );

    sh.cp('-R', 'src/components/_template', newComponentFolderPath);
    sh.mv(templateComponentFilePath, newComponentFilePath);

    const newFile = fs.readFileSync(newComponentFilePath, { encoding: 'utf8' });

    fs.writeFileSync(
        newComponentFilePath,
        newFile.replace('SBProTEMPLATE', pascalCase(options.name)),
    );
}

main();
